package com.chejianer.phone.domain;

import com.chejianer.phone.utils.CheckSumBuilder;
import com.chejianer.phone.utils.CreateNonce;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Chejianer on 2016/8/26.
 */
public class CreateAccid {
    public static String createId(String accid)throws Exception{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "https://api.netease.im/nimserver/user/create.action";
        HttpPost httpPost = new HttpPost(url);

        /**
         * appkey与appSecret是你注册网易云信并创建的应用的对应d的内容
         * 登录网易云信可在你的项目管理上看到
         */
        String appKey = "your key";
        String appSecret = "your secret";
        String nonce =  CreateNonce.getNonce();
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", accid));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);

        String result=EntityUtils.toString(response.getEntity(),"UTF-8");
        // 打印执行结果
        System.out.println(result);
        return result;
    }
}
